/**
 * APP 应用  布局文件
 *
 *
 */
import {setAuth} from '@/store/action/user';
//路由配置
import {NavigationContainer} from '@react-navigation/native';
import React, {Component} from 'react';
import {StyleSheet, Alert} from 'react-native';
import Toast from 'react-native-root-toast';
import {navigationRef} from '@/utils/rootNavigation';
import * as RootNavigation from '@/utils/rootNavigation';
import {RootSiblingParent} from 'react-native-root-siblings';
import {getUserInfo} from '@/apis/api';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {AppState} from 'react-native';
//应用状态管理
import {Provider} from 'react-redux';
import store from '@/store';
import {SafeAreaView, StatusBar, View} from 'react-native';
import {stackRoutes} from '@/routes';
import { i18n, initI18n } from '@/language/i18n';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();
import SplashScreen from 'react-native-splash-screen';
import StorageUtils from '@/utils/storageUtils';
import {ThemeConfig} from '@/assets/styles/layout';
import {getLatestAppApkVersion, getLatestAppApkDownloadUrl} from '@/apis/api';
import RNFetchBlob from 'rn-fetch-blob';
import {
  APP_CODE as appCode,
  BASE_URL as baseUrl,
  DEVICE_TYPE as deviceType,
  APP_NAME as appName,
  VERSION_NAME as versionName,
} from './app.json';
import {withTranslation} from 'react-i18next';
interface IState {
  userToken: string;
}

class App extends Component {
  constructor(props: any) {
    super(props);
    SplashScreen.hide(); // 关闭启动屏幕
  }

  readonly state: IState = {
    userToken: '', // token 信息
  };

  download = async (latestVersion: any) => {
    const {t} = this.props;
    const params = {
      appCode,
      baseUrl,
      deviceType,
      versionName: latestVersion,
    };
    getLatestAppApkDownloadUrl(params).then(res => {
      if (res?.data) {
        // 指定包含最新版本的安装包文件的 URL
        const fileUrl = res?.data;
        const android = RNFetchBlob.android;
        let timestamp = new Date().getTime();
        // 文件保存路径
        const downloadDest = `${RNFetchBlob.fs.dirs.DownloadDir}/${appCode}-${timestamp}.apk`;
        Toast.show(t('sys_packageDownloadBackend'), {
          duration: 1000,
          position: Toast.positions.BOTTOM,
        });
        RNFetchBlob.config({
          fileCache: true,
          addAndroidDownloads: {
            useDownloadManager: true,
            // notification: true,
            mediaScannable: true,
            title: `${appCode}-${timestamp}.apk`,
            path: downloadDest,
          },
        })
          .fetch('GET', fileUrl, {})
          .then(res => {
            //下载成功后自动打开安装已下载apk文件
            android.actionViewIntent(
              res.path(),
              'application/vnd.android.package-archive',
            );
            console.log('The file saved to ', res.path());
          })
          .catch(error => {
            Toast.show(t('sys_fileDownloadFail'), {
              duration: 1000,
              position: Toast.positions.CENTER,
            });
          });
      }
    });
  };
  getLatestUpgradeVersion = async () => {
    const data = {
      appCode,
      baseUrl,
      deviceType,
      versionName,
    };
    // 获取最新的安装包版本
    getLatestAppApkVersion(data).then(async res => {

      const {t} = this.props;
      const latestVersion = res?.data;

      if (res?.data && latestVersion !== versionName) {
        // 存在新版本
        Alert.alert(t('sys_tip'), t('sys_newVersionUpdateConfirm'), [
          {
            text: t('sys_cancel'),
            onPress: () => {},
            style: 'cancel',
          },
          {
            text: t('sys_update'),
            onPress: () => {
              this.download(res?.data);
            },
          },
        ]);
      }
    });
  };

  _handleAppStateChange = nextAppState => {
    if (nextAppState === 'active') {
      // this.getLatestUpgradeVersion();
    }
  };

  async componentDidMount() {
    console.log('componentDidMount------')
    await initI18n();
    const auth = await StorageUtils.getItem('auth');
    if (auth) {
      try {
        await getUserInfo();
        store.dispatch(setAuth(auth));
        this.getLatestUpgradeVersion();
        // AppState.addEventListener('change', this._handleAppStateChange);
      } catch {
        await StorageUtils.removeItem('auth');
        RootNavigation.reset('Login');
      }
    } else {
      RootNavigation.reset('Login');
    }
    this.setState({userToken: auth?.access_token || ''});
  }

  getMainStack = () => {
    const {t} = this.props;
    return (
      <Stack.Navigator
        initialRouteName="Layout"
        screenOptions={{
          headerBackVisible: false,
          headerShown: false,
          headerTitleAlign: 'center',
          headerTintColor: '#fff',
          headerStyle: {
            backgroundColor: '#0052d9', // 设置导航栏背景颜色
          },
          headerTitleStyle: {
            fontWeight: 'bold',
            color: '#fff',
            fontSize: 16,
          },
        }}>
        {stackRoutes?.length &&
          stackRoutes.map((route: any) => {
            return (
              <Stack.Screen
                name={route.name}
                component={route.component}
                key={route.name}
                options={{title: t(route.labelName)}}
              />
            );
          })}
      </Stack.Navigator>
    );
  };

  render() {
    return (
      <RootSiblingParent>
        <StatusBar backgroundColor="#0052d9" />
        <GestureHandlerRootView style={styles.root}>
          <NavigationContainer ref={navigationRef}>
            <Provider store={store}>{this.getMainStack()}</Provider>
          </NavigationContainer>
        </GestureHandlerRootView>
      </RootSiblingParent>
    );
  }
}

export default withTranslation()(App);
const styles = StyleSheet.create({
  root: {
    flex: 1,
  },
});
